package com.kly.cashmall.module.home.home_tab.tab_view;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.fragment.app.Fragment;

import com.kly.cashmall.R;
import com.kly.cashmall.utils.function.BundleHelper;
import com.kly.cashmall.utils.data.TextUtil;
import com.kly.cashmall.utils.ViewHolder;


/**
 * @author
 * @date 2018/1/3
 */
public class HomeTabItem implements TabItem {

  private View tabView;
  private FragmentPackage<MenuTabInfo> fp;
  private Fragment fragment;




  public HomeTabItem(Context context, FragmentPackage<MenuTabInfo> fp) {
    this.fp = fp;
    this.tabView = LayoutInflater.from(context).inflate(R.layout.layout_home_tab_item, null);
    initView();
  }

  private void initView() {
    ViewHolder.getHolder(tabView).setText(R.id.tab_text, fp.data.title);

    MenuImageView menuImageView = ViewHolder.getHolder(tabView).get(R.id.tab_icon);
    if (TextUtil.isEmpty(fp.data.imgUrl) || TextUtil.isEmpty(fp.data.imgCheckedUrl)) {
      menuImageView.setImageResource(fp.data.iconResource);
    } else {
      menuImageView.setSelectUrls(fp.data.imgCheckedUrl,fp.data.imgUrl);
    }
  }

  @Override
  public View getTabView() {
    return tabView;
  }

  @Override
  public Fragment getFragment() {

    if (fragment == null) {
      fragment = newFragment(fp.fragmentClass);
      fragment.setArguments(
          BundleHelper.create().putSerializable(MenuTabInfo.TAG_INFO, fp.data).get());
    }

    return fragment;
  }

  /**
   * 反射生成Fragment
   */
  private static Fragment newFragment(Class<? extends Fragment> clazz) {

    Fragment fragment = null;
    try {
      fragment = clazz.newInstance();
      Log.e("newFragment", "fragment:" + fragment);
    } catch (InstantiationException e) {
      Log.e("newFragment", e.getMessage());
      e.printStackTrace();
    } catch (Exception e) {
      Log.e("newFragment", e.getMessage());
      e.printStackTrace();
    }

    return fragment;
  }

  @Override
  public String getTag() {
    if (getFragment() == null) {
      return "";
    }

    return TagStaticMap.findTagName(getFragment().getClass());
  }

  @Override
  public void setRedDot(boolean visible) {
    ViewHolder.getHolder(this.tabView).setVisible(R.id.tab_remind_dot, visible);
  }

  @Override
  public int judgeNeedLogin() {
    return fp.data.needLogin();
  }
}
